import type { FormInstance } from 'element-plus'

// 新增还是编辑
type dialogType = 'add' | 'edit'
/**
 * 分页封装
 * @param {Function} dataPageApi 获取数据的API方法
 * @param {Function} dataBatchDelApi 删除的API方法
 * @param {Object} queryParams 除固定的分页参数额外查询参数
 * @param {Ref} queryFormRef 查询表单的FormRef对象
 * @param {Object} addEditFormRef 新增编辑组件Ref对象
 * @returns {Function} getDataFn 获取接口数据
 * @returns {Function} handleQuery 查询方法
 * @returns {Function} handleResetQuery 重置查询方法
 * @returns {Function} handleAddEdit 新增编辑方法
 * @returns {Function} handleDelete 删除方法
 * @returns {Function} handleSelectChange 行选择方法
 * @author lxx
 */
export const usePage = <T extends { id: number | null }>(
  dataPageApi: (params: any) => Promise<any>,
  dataBatchDelApi: (ids: number[]) => Promise<any>,
  queryParams: Ref<Record<string, any>>,
  queryFormRef: Ref<FormInstance>,
  addEditFormRef: Ref<any>
) => {
  // 分页参数
  const queryPage = reactive({
    keywords: '',
    pageNum: 1,
    pageSize: 10,
    total: 0
  })
  // 列表加载状态
  const loading = ref(false)

  // 表格数据
  const tableData = ref<T[]>([])

  // 获取列表数据
  const getDataFun = async () => {
    try {
      loading.value = true
      const res = await dataPageApi({
        ...queryPage,
        ...queryParams.value
      })

      if (res?.code === 200) {
        tableData.value = res.data?.records || []
        queryPage.total = res.data?.total || 0
      } else {
        tableData.value = []
        queryPage.total = 0
      }
    } catch (error) {
      console.error('Failed to fetch data:', error)
      tableData.value = []
      queryPage.total = 0
    } finally {
      loading.value = false
    }
  }

  // 查询按钮
  const handleQuery = () => {
    getDataFun()
  }

  /**
   * @description: 重置查询
   * @author: lxx
   * @date: 2025-07-03 23:26:06
   */
  const handleResetQuery = () => {
    if (queryFormRef.value) {
      queryFormRef.value.resetFields()
    }
    queryPage.pageNum = 1
    getDataFun()
  }

  /**
   * @description: 新增、修改
   * @author: lxx
   * @date: 2025-07-03 16:42:06
   */
  const handleAddEdit = (type: dialogType, rowData?: T) => {
    addEditFormRef.value.open(type, rowData)
  }

  // 删除相关
  const ids = ref<number[]>([])
  /**
   * @description: 删除字典
   * @param id 字典ID
   * @author: lxx
   * @date: 2025-07-03 16:42:06
   */
  function handleDelete(id?: number) {
    const attrGroupIds = id ? [id] : ids.value
    if (attrGroupIds.length == 0) {
      ElMessage.warning('请勾选删除项')
      return
    }
    ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(
      () => {
        dataBatchDelApi(attrGroupIds).then(() => {
          ElMessage.success('删除成功')
          handleResetQuery()
        })
      },
      () => {
        ElMessage.info('已取消删除')
      }
    )
  }
  // 行选择
  function handleSelectChange(rowData: T[]) {
    ids.value = rowData.map((item: T) => item.id) as number[]
  }

  onMounted(() => {
    getDataFun()
  })

  /**
   * 提供给子组件使用的方法
   * @returns {Function} handleQuery
   * @returns {Function}handleResetQuery
   */
  provide('listObj', {
    handleQuery,
    handleResetQuery
  })

  return {
    queryPage,
    loading,
    tableData,
    getDataFun,
    handleQuery,
    handleResetQuery,
    handleAddEdit,
    handleDelete,
    handleSelectChange
  }
}

/**
 * 新增编辑封装
 * @param {Function} dataSaveApi 保存数据的API方法
 * @param {Object} formData 表单项新增/编辑参数
 * @returns {Ref} formDataRef 表单的FormRef对象
 * @author lxx
 */
export const useAddEdit = <T>(dataSaveApi: (params: any) => Promise<any>, formData: Ref<Record<string, any>>, formDataRef: Ref<FormInstance>, loadFormDataSuccess?: (data: T) => void) => {
  // 获取父组件对象
  const listObj: any = inject('listObj')

  // 是否编辑
  const isEdit = ref(false)

  const loading = ref(false)

  const dialog = reactive({
    title: '',
    visible: false
  })

  // 打开弹框
  const open = (type: 'add' | 'edit', data?: T) => {
    dialog.visible = true
    nextTick(() => {
      if (type === 'edit') {
        isEdit.value = true
        dialog.title = '修改'
        Object.assign(formData.value, data)
        loadFormDataSuccess && loadFormDataSuccess(data as T)
      } else {
        isEdit.value = false
        dialog.title = '新增'
      }
    })
  }

  // 关闭弹窗
  function handleCloseDialog() {
    if (formDataRef.value) {
      formDataRef.value.resetFields()
      formDataRef.value.clearValidate()
      formData.value.id = null
    }

    nextTick(() => {
      dialog.visible = false
    })
  }

  /**
   * 提交字典表单
   * @param flag 为true时，为连续添加不清空数据
   */
  function handleSubmitClick(flag?: boolean) {
    formDataRef.value.validate((isValid: boolean, fields: any) => {
      if (isValid) {
        loading.value = true
        const reqData = {
          ...formData.value
        }
        if (formData.value.id == -1) {
          reqData.id = null
        }
        dataSaveApi(reqData)
          .then(() => {
            ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
            if(!flag) {
              handleCloseDialog()
            }
            listObj.handleResetQuery()
          })
          .finally(() => (loading.value = false))
      } else {
        try {
          // 提示具体的错误信息
          if (fields) {
            for (const key in fields) {
              ElMessage.error(fields[key][0].message)
              break
            }
          }
        } catch (error) {
          ElMessage.error('异常！')
          
        }
       
      }
    })
  }

  return {
    // 是否编辑页面
    isEdit,
    // 接收父级抛出
    listObj,
    // 加载中
    loading,
    // 弹框使用的对象
    dialog,
    // 弹框打开方法
    open,
    // 弹框关闭方法
    handleCloseDialog,
    // 表单提交方法
    handleSubmitClick
  }
}
